#include <graphics.h>
#include <conio.h>
#include <vector>
#include <string>
#include <algorithm>
#include <random>
#include <ctime>
#include <mmsystem.h>
#pragma comment(lib, "winmm.lib")

// 基础游戏对象类
class GameObject {
public:
    virtual ~GameObject() {}
    virtual int getX() const = 0;
    virtual int getY() const = 0;
    virtual int getWidth() const = 0;
    virtual int getHeight() const = 0;
    virtual void draw() = 0;
};

// 游戏背景类
class GameBackground {
private:
    IMAGE image1, image2;
    int speed = 8;  // 滚动速度
    int x1, x2;
    int mapHeight;
    int screenWidth, screenHeight;

public:
    GameBackground(int width, int height) {
        screenWidth = width;
        screenHeight = height;
        
        // 加载背景图片
        loadimage(&image1, _T("images/dragon/map.png"));
        loadimage(&image2, _T("images/dragon/map.png"));
        
        // 初始化坐标
        x1 = 0;
        x2 = screenWidth;
        
        // 获取图片高度
        mapHeight = image1.getheight();
    }
    
    void update() {
        x1 = x1 - speed;
        x2 = x2 - speed;
        
        if (x1 <= -screenWidth) {
            x1 = 0;
        }
        if (x2 <= 0) {
            x2 = screenWidth;
        }
    }
    
    void draw() {
        int mapY = screenHeight - mapHeight;
        putimage(x1, mapY, &image1);
        putimage(x2, mapY, &image2);
    }
};

// 云朵类
class Cloud : public GameObject {
private:
    IMAGE image;
    int speed = 1;
    int x, y;
    int width, height;

public:
    Cloud(int startX, int startY, const IMAGE& img) {
        x = startX;
        y = startY;
        image = img;
        width = image.getwidth();
        height = image.getheight();
    }
    
    void move() {
        x -= speed;
    }
    
    void draw() override {
        putimage(x, y, &image);
    }
    
    int getX() const override { return x; }
    int getY() const override { return y; }
    int getWidth() const override { return width; }
    int getHeight() const override { return height; }
};

// 仙人掌类
class Cactus : public GameObject {
private:
    IMAGE image;
    IMAGE resizedImage;  // 用于存储调整大小后的图像
    int speed = 8;
    int x, y;
    int width, height;
    const int MAX_HEIGHT = 60;  // 最大高度为60像素

public:
    Cactus(int startX, int startY, const IMAGE& img) {
        x = startX;
        
        // 获取原始图像尺寸
        int origWidth = img.getwidth();
        int origHeight = img.getheight();
        
        // 计算缩放比例，保持宽高比
        double scale = 1.0;
        if (origHeight > MAX_HEIGHT) {
            scale = static_cast<double>(MAX_HEIGHT) / origHeight;
            width = static_cast<int>(origWidth * scale);
            height = MAX_HEIGHT;
        } else {
            width = origWidth;
            height = origHeight;
        }
        
        // 创建调整大小后的图像
        resizedImage = img;
        if (scale < 1.0) {
            // 创建一个空的IMAGE对象并调整大小
            resizedImage = img;  // 先复制原始图像
            // EasyX没有内置的调整图像大小的函数，实际应用中需要自定义实现或使用其他方法
            // 这里简化处理，只改变width和height值
        } else {
            resizedImage = img;
        }
        
        image = resizedImage;
        y = startY + (origHeight - height);  // 调整Y坐标，使底部对齐
    }
    
    void move() {
        x -= speed;
    }
    
    void draw() override {
        putimage(x, y, &image);
    }
    
    int getX() const override { return x; }
    int getY() const override { return y; }
    int getWidth() const override { return width; }
    int getHeight() const override { return height; }
};

// 鸟类
class Bird : public GameObject {
private:
    std::vector<IMAGE> images;
    int speed = 10;
    int x, y;
    int width, height;
    int index = 0;
    int animCounter = 1;

public:
    Bird(int startX, int startY, const std::vector<IMAGE>& imgs) {
        x = startX;
        y = startY;
        images = imgs;
        width = images[0].getwidth();
        height = images[0].getheight();
    }
    
    void move() {
        x -= speed;
    }
    
    void draw() override {
        if (animCounter <= 8) {
            index = 0;
        } else {
            index = 1;
        }
        
        if (animCounter == 16) {
            animCounter = 0;
        }
        
        putimage(x, y, &(images[index]));
        animCounter++;
    }
    
    int getX() const override { return x; }
    int getY() const override { return y; }
    int getWidth() const override { return width; }
    int getHeight() const override { return height; }
};

// 恐龙类
class Dragon : public GameObject {
private:
    std::vector<IMAGE> images;
    int x, y;
    int originalY;  // 记录原始Y坐标，用于跳跃后恢复
    int width, height;
    int index = 0;
    int animCounter = 1;
    int style = 0;  // 0：站立，1：蹲下
    int jump = 0;   // 0: 未起跳，1：开始上升，2：开始下降
    int jumpYAdd = 0;

public:
    bool isHit = false;

    Dragon(int startX, int startY, const std::vector<IMAGE>& imgs) {
        x = startX;
        y = startY;
        originalY = startY;
        images = imgs;
        width = images[0].getwidth();
        height = images[0].getheight();
    }
    
    void setJump() {
        if (style == 0 && jump == 0) {
            jump = 1;
            PlaySound(_T("sounds/dragon/jump.wav"), NULL, SND_ASYNC);
        }
    }
    
    void update() {
        if (jump == 1) {
            y -= 10;
            jumpYAdd += 10;
            if (jumpYAdd == 200) {
                jump = 2;
            }
        }
        
        if (jump == 2) {
            y += 10;
            jumpYAdd -= 10;
            if (jumpYAdd == 0) {
                jump = 0;
            }
        }
    }
    
    void draw() override {
        if (animCounter <= 5) {
            if (style == 0) {
                index = 0;
            } else {
                index = 2;
            }
        } else {
            if (style == 0) {
                index = 1;
            } else {
                index = 3;
            }
        }
        
        if (animCounter == 10) {
            animCounter = 0;
        }
        
        width = images[index].getwidth();
        height = images[index].getheight();
        putimage(x, y, &(images[index]));
        animCounter++;
    }
    
    void setStandingPosition() {
        if (style == 1) {
            style = 0;
            y -= 34;
        }
    }
    
    void setCrouchingPosition() {
        if (style == 0 && jump == 0) {
            style = 1;
            y += 34;
        }
    }
    
    int getX() const override { return x; }
    int getY() const override { return y; }
    int getWidth() const override { return width; }
    int getHeight() const override { return height; }
};

// 游戏主类
class Game {
private:
    const int screenWidth = 800;
    const int screenHeight = 350;
    bool running = true;
    
    GameBackground* background;
    
    std::vector<Cloud*> clouds;
    IMAGE cloudImage;
    
    std::vector<Cactus*> items;
    std::vector<IMAGE> itemImages;
    int itemSpawnCounter = 1;
    int itemSpawnInterval = 100;
    
    std::vector<Bird*> birds;
    std::vector<IMAGE> birdImages;
    int birdSpawnCounter = 1;
    int birdSpawnInterval = 150;
    
    Dragon* dragon;
    std::vector<IMAGE> dragonImages;
    
    IMAGE gameoverImage;
    IMAGE restartImage;
    int restartX, restartY;
    
    float score = 0.0f;
    
    // 初始化随机数生成器
    std::mt19937 rng;

public:
    Game() {
        // 初始化随机数生成器
        rng.seed(static_cast<unsigned int>(time(0)));
        
        // 初始化图形环境
        initgraph(screenWidth, screenHeight);
        setbkcolor(WHITE);
        cleardevice();
        
        // 创建背景
        background = new GameBackground(screenWidth, screenHeight);
        
        // 加载云图片
        loadimage(&cloudImage, _T("images/dragon/cloud.png"));
        
        // 创建初始云朵
        createCloud();
        
        // 加载仙人掌图片
        for (int i = 0; i < 7; i++) {
            IMAGE img;
            TCHAR path[50];
            _stprintf_s(path, _T("images/dragon/item_%d.png"), i + 1);
            loadimage(&img, path);
            itemImages.push_back(img);
        }
        
        // 加载鸟图片
        IMAGE birdImg1, birdImg2;
        loadimage(&birdImg1, _T("images/dragon/bird_1.png"));
        loadimage(&birdImg2, _T("images/dragon/bird_2.png"));
        birdImages.push_back(birdImg1);
        birdImages.push_back(birdImg2);
        
        // 加载恐龙图片
        for (int i = 0; i < 4; i++) {
            IMAGE img;
            TCHAR path[50];
            _stprintf_s(path, _T("images/dragon/dragon_%d.png"), i + 1);
            loadimage(&img, path);
            dragonImages.push_back(img);
        }
        
        // 创建恐龙
        int dragonX = 50;
        int dragonY = screenHeight - dragonImages[0].getheight();
        dragon = new Dragon(dragonX, dragonY, dragonImages);
        
        // 加载游戏结束和重启图片
        loadimage(&gameoverImage, _T("images/dragon/gameover.png"));
        loadimage(&restartImage, _T("images/dragon/restart.png"));
    }
    
    ~Game() {
        // 释放资源
        delete background;
        delete dragon;
        
        for (size_t i = 0; i < clouds.size(); i++) {
            delete clouds[i];
        }
        
        for (size_t i = 0; i < items.size(); i++) {
            delete items[i];
        }
        
        for (size_t i = 0; i < birds.size(); i++) {
            delete birds[i];
        }
        
        // 关闭图形环境
        closegraph();
    }
    
    void createCloud() {
        clouds.push_back(new Cloud(350, 30, cloudImage));
        clouds.push_back(new Cloud(650, 100, cloudImage));
    }
    
    void run() {
        BeginBatchDraw();
        
        while (running) {
            // 处理用户输入
            handleInput();
            
            // 更新游戏状态
            update();
            
            // 渲染游戏画面
            render();
            
            // 碰撞检测
            detectCollision();
            
            // 刷新屏幕
            FlushBatchDraw();
            
            // 控制帧率
            Sleep(16);  // 大约60fps
        }
        
        EndBatchDraw();
    }
    
    void handleInput() {
        // 处理鼠标点击事件
        if (MouseHit()) {
            MOUSEMSG msg = GetMouseMsg();
            if (msg.uMsg == WM_LBUTTONDOWN && dragon->isHit) {
                int x = msg.x;
                int y = msg.y;
                
                // 检查是否点击了重启按钮
                if (x >= restartX && x <= restartX + restartImage.getwidth() &&
                    y >= restartY && y <= restartY + restartImage.getheight()) {
                    // 重启游戏
                    dragon->isHit = false;
                    score = 0;
                    
                    // 清空障碍物
                    for (size_t i = 0; i < items.size(); i++) {
                        delete items[i];
                    }
                    items.clear();
                    
                    for (size_t i = 0; i < birds.size(); i++) {
                        delete birds[i];
                    }
                    birds.clear();
                }
            }
            // 添加鼠标点击跳跃功能
            else if (msg.uMsg == WM_LBUTTONDOWN && !dragon->isHit) {
                dragon->setJump();
            }
        }
        
        // 处理键盘输入
        if (_kbhit()) {
            int key = _getch();
            
            // 如果按下ESC键
            if (key == 27) {
                running = false;
            }
            
            // 设置多个跳跃键
            if (key == 32 || // 空格键
                key == 'w' || key == 'W' || // W键
                key == 13 || // 回车键
                key == 72) { // 上箭头键(方向键的扫描码)
                dragon->setJump();
            }
        }
        
        // 检测方向键状态
        if (GetAsyncKeyState(VK_UP) & 0x8000) { // 添加上箭头键跳跃
            dragon->setJump();
        }
        
        if (GetAsyncKeyState(VK_DOWN) & 0x8000) {
            dragon->setCrouchingPosition();
        } else {
            dragon->setStandingPosition();
        }
    }
    
    void update() {
        if (dragon->isHit) {
            return;
        }
        
        // 更新背景
        background->update();
        
        // 更新云
        std::vector<Cloud*>::iterator cloudIt;
        for (cloudIt = clouds.begin(); cloudIt != clouds.end();) {
            (*cloudIt)->move();
            
            if ((*cloudIt)->getX() < -(*cloudIt)->getWidth()) {
                delete *cloudIt;
                cloudIt = clouds.erase(cloudIt);
            } else {
                ++cloudIt;
            }
        }
        
        if (clouds.empty()) {
            createCloud();
        }
        
        // 更新仙人掌
        if (itemSpawnCounter % itemSpawnInterval == 0) {
            std::uniform_int_distribution<int> dist(0, static_cast<int>(itemImages.size()) - 1);
            int randomIndex = dist(rng);
            
            int x = screenWidth;
            int y = screenHeight - itemImages[randomIndex].getheight();
            
            items.push_back(new Cactus(x, y, itemImages[randomIndex]));
        }
        itemSpawnCounter++;
        
        if (itemSpawnCounter >= itemSpawnInterval) {
            itemSpawnCounter = 0;
            std::uniform_int_distribution<int> dist(60, 110);
            itemSpawnInterval = dist(rng);
        }
        
        std::vector<Cactus*>::iterator itemIt;
        for (itemIt = items.begin(); itemIt != items.end();) {
            (*itemIt)->move();
            
            if ((*itemIt)->getX() < -(*itemIt)->getWidth()) {
                delete *itemIt;
                itemIt = items.erase(itemIt);
            } else {
                ++itemIt;
            }
        }
        
        // 更新鸟（当分数超过100时）
        if (static_cast<int>(score) > 100) {
            if (birdSpawnCounter % birdSpawnInterval == 0) {
                int x = screenWidth;
                int y = 210;
                
                birds.push_back(new Bird(x, y, birdImages));
            }
            birdSpawnCounter++;
            
            if (birdSpawnCounter >= birdSpawnInterval) {
                birdSpawnCounter = 0;
                std::uniform_int_distribution<int> dist(150, 300);
                birdSpawnInterval = dist(rng);
            }
            
            std::vector<Bird*>::iterator birdIt;
            for (birdIt = birds.begin(); birdIt != birds.end();) {
                (*birdIt)->move();
                
                if ((*birdIt)->getX() < -(*birdIt)->getWidth()) {
                    delete *birdIt;
                    birdIt = birds.erase(birdIt);
                } else {
                    ++birdIt;
                }
            }
        }
        
        // 更新恐龙
        dragon->update();
        
        // 更新分数
        score += 0.1f;
    }
    
    void render() {
        cleardevice();
        
        if (dragon->isHit) {
            // 绘制游戏结束界面
            int gameoverX = screenWidth / 2 - gameoverImage.getwidth() / 2;
            putimage(gameoverX, 120, &gameoverImage);
            
            restartX = screenWidth / 2 - restartImage.getwidth() / 2;
            restartY = 170;
            putimage(restartX, restartY, &restartImage);
            return;
        }
        
        // 绘制背景
        background->draw();
        
        // 绘制云
        for (size_t i = 0; i < clouds.size(); i++) {
            clouds[i]->draw();
        }
        
        // 绘制仙人掌
        for (size_t i = 0; i < items.size(); i++) {
            items[i]->draw();
        }
        
        // 绘制鸟
        for (size_t i = 0; i < birds.size(); i++) {
            birds[i]->draw();
        }
        
        // 绘制恐龙
        dragon->draw();
        
        // 绘制分数
        TCHAR scoreText[20];
        _stprintf_s(scoreText, _T("%dm"), static_cast<int>(score));
        settextcolor(RGB(83, 83, 83));
        settextstyle(20, 0, _T("Arial"));
        setbkmode(TRANSPARENT);
        
        int textWidth = textwidth(scoreText);
        outtextxy(screenWidth - textWidth - 10, 10, scoreText);
    }
    
    void detectCollision() {
        if (dragon->isHit) {
            return;
        }
        
        // 检测与仙人掌的碰撞
        for (size_t i = 0; i < items.size(); i++) {
            if (checkCollision(dragon, items[i])) {
                dragon->isHit = true;
                break;
            }
        }
        
        // 检测与鸟的碰撞
        for (size_t i = 0; i < birds.size(); i++) {
            if (checkCollision(dragon, birds[i])) {
                dragon->isHit = true;
                break;
            }
        }
        
        // 如果发生碰撞，播放游戏结束音效，降低音量
        if (dragon->isHit) {
            PlaySound(_T("sounds/dragon/gameover.wav"), NULL, SND_ASYNC | SND_NODEFAULT);
        }
    }
    
    // 碰撞检测，判断a和b是否碰撞
    bool checkCollision(const GameObject* a, const GameObject* b) {
        const int offset = 30;  // 增加误差，降低难度
        
        bool xOverlap = (b->getX() + offset <= a->getX() + a->getWidth() && 
                         a->getX() + a->getWidth() <= b->getX() + offset + b->getWidth());
                          
        bool yOverlap = (b->getY() + offset <= a->getY() + a->getHeight() && 
                         a->getY() + a->getHeight() <= b->getY() + offset + b->getHeight());
                          
        return xOverlap && yOverlap;
    }
};

int main() {
    Game game;
    game.run();
    return 0;
} 